package com.cuitrip.business.user;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.PlatformUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.network.proxy.ApiProxyBuilder;
import com.lab.network.proxy.ApiProxyCallBack;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.MessageUtils;
import com.lab.utils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by MiJack on 2016/1/12.
 */
public class ModifyUserLanguageActivity extends CustomUiFragmentActivity{

    @Bind(R.id.listView)
    ListView listView;
    @Bind(R.id.state_layout)
    StateLayout stateLayout;
    ApiProxy apiProxy;
    private IProxyCallback languageCallback = new ApiProxyCallBack<Languages>() {
        @Override
        public void doPreWork(CtApiResponse response) {
            hideLoading();
        }

        @Override
        public boolean onSuccess(Languages languages, CtApiResponse response) {
            hideNoCancelDialog();
            if (languages == null) {
                return false;
            }
            List<Language> list = new ArrayList<>();
            for (Language language : languages.list) {
                list.add(language);
            }
            adapter.setDatas(list);
            CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
            for (int i = 0; i < list.size(); i++) {
                Language language = list.get(i);
                listView.setItemChecked(i, (userInfo.getLanguageCode() & language.V) == language.V);
            }
            return false;
        }
    };
    private IProxyCallback modifyCallback =new ApiProxyCallBack<CtUserInfo>(){
        @Override
        public void doPreWork(CtApiResponse response) {
            hideNoCancelDialog();
        }

        @Override
        public boolean onSuccess(CtUserInfo data, CtApiResponse response) {
//            String language = data.getLanguage();
            LoginInstance.updateProfile(AppCoreRuntime.context,data, false);
//            LoginInstance.getInstance().getUserInfo().setLanguage(language);
            finish();
            ToastUtil.toast(R.string.feedback_edit_suc);
            return super.onSuccess(data, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            String msg;
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                msg = response.msg;
            } else {
                msg = PlatformUtil.getInstance().getString(R.string.feedback_data_err);
            }
            MessageUtils.showToast(msg);
            return super.onFaild(response);
        }
    };
    private LanguageAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.ct_activity_modify_language);
    }

    @Override
    public void initData() {
        ButterKnife.bind(this);
        adapter = new LanguageAdapter();
        listView.setAdapter(adapter);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        //获取语言的字典
        apiProxy = ApiProxyBuilder
                .getBuilder()
                .addApiCallBack(ApiManager.GET_LANGUAGE_LIST, languageCallback)
                .addApiCallBack(ApiManager.MODIFY_USERINFO, modifyCallback)
                .build();
        requestLanguages();
        stateLayout.setOnClickStateLayoutListener(new StateLayout.OnClickStateLayoutListener() {
            @Override
            public void onClick(StateLayout.State state) {
                requestLanguages();
            }
        });
    }

    private void requestLanguages() {
        showLoading(false);
        UserBusiness.getLanguageList(apiProxy);
    }


    public static class Languages {
        public List<Language> list;
    }

    public static class Language {
        public String K;
        public int V;
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mLeftStyle = CustomUiConfig.AreaStyle.ICON_STYLE;
        config.mRightStyle = CustomUiConfig.AreaStyle.TEXT_STYLE;
        config.mTopbarMiddleAreaName = getString(R.string.user_attribute_language);
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarRightAreaName = getString(R.string.operation_ok_1);
        return config;
    }

    @Override
    public void onTopbarLeftPress() {
        finish();
    }

    @Override
    public void onTopbarRightPress() {
        //更新语言
        if (listView.getCheckedItemCount()==0){
            ToastUtil.toast(R.string.user_attribute_language_desc);
            return;
        }
        int languageValue = 0;
        for (int i=0;i<adapter.getCount();i++){
            if (!listView.isItemChecked(i)){
                continue;
            }
            languageValue+=adapter.getItem(i).V;
        }
        showNoCancelDialog();
        Map<String,String> map=new HashMap<>();
        map.put("language", String.valueOf(languageValue));
        UserBusiness.updateProfile(apiProxy,map);
    }
    private static class LanguageAdapter extends BaseAdapter {

        private List<Language> datas;

        public LanguageAdapter() {
        }

        @Override
        public int getCount() {
            return datas == null ? 0 : datas.size();
        }

        @Override
        public Language getItem(int position) {
            return datas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.ct_checkable_list_item, parent, false);
                holder = new ViewHolder();
                holder.language = (TextView) convertView.findViewById(R.id.simple_text);
                holder.tvState = (IconTextView) convertView.findViewById(R.id.icon);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.language.setText(getItem(position).K);
            return convertView;
        }

        public void setDatas(List<Language> languages) {
            if (datas == null) {
                datas = new ArrayList<>();
            } else {
                datas.clear();
            }
            datas.addAll(languages);
            notifyDataSetChanged();
        }

        private static final class ViewHolder {
            TextView language;
            IconTextView tvState;
        }
    }
}
